package com.teng.dataStructure.stack;

import java.util.Stack;
/*
 栈在Java中的常用方法
 1、pop：取出顶部元素
 2、push：存入元素
 3、peek：展示顶部元素 ——> stack.peek() == null 即表示栈空
 */
public class operationStack {
    public static void main(String[] args) {
        Stack<String> operStack = new Stack<>(); // 符号栈
        Stack<Integer> numStack = new Stack<>(); // 数字栈
        int num1 = 0;
        int num2 = 0;
        int result = 0;
        String[] target = {"5","*","8","-", "4", "+", "135"};
        for (int i = 0; i < target.length; i++) {
            String str = target[i];
            if (isOper(str)) {
                // 1、判断栈空
                // 2、如果非空，判断现在的元素和栈内顶部元素的运算优先级
                //  2.1、如果现元素优先级更大，则取出数字栈的第一个元素和下一个输入的元素进行运算后将结果存入数字栈
                //  2.2、反之则存入符号栈
                if (operLevel(str) == 1) {
                    i++;
                    num2 = numStack.pop();
                    num1 = Integer.parseInt(target[i]);
                    result = cal(num1, num2, str);
                    numStack.push(result);
                } else {
                    operStack.push(str);
                }
/*                if (operStack.isEmpty()) {
                    operStack.push(key);
                } else {
                    if (operLevel(str) == 1) {
                        i++;
                        num2 = numStack.pop();
                        num1 = Integer.parseInt(target[i]);
                        result = cal(num1, num2, str);
                        numStack.push(result);
                    } else {
                        operStack.push(key);
                    }
                }*/
            } else {
                numStack.push(Integer.parseInt(str));
            }
        }
        while (!operStack.isEmpty()) {
            num2 = numStack.pop();
            num1 = numStack.pop();
            String str = operStack.pop();
            result = cal(num1, num2, str);
            numStack.push(result);
        }
        System.out.println("结果为：" + numStack.pop());
    }


    /*
    返回运算符的优先级: 优先级使用数字表示
    数字越大，优先级越高
     */
    public static int operLevel(String oper) {
        if ("/".equals(oper) || "*".equals(oper)) {
            return 1;
        } else if ("+".equals(oper) || "-".equals(oper)) {
            return 0;
        } else {
            return -1;
        }
    }

    /*
    判断当前输入是否是运算符
     */
    public static boolean isOper(String oper) {
        return "+".equals(oper) || "-".equals(oper) || "*".equals(oper) || "/".equals(oper);
    }

    /*
    计算方法
     */
    public static int cal (int num1, int num2, String oper) {
        if ("+".equals(oper)) {
            return num2 - num1;
        } else if ("-".equals(oper)) {
            return num2 - num1;
        } else if ("*".equals(oper)) {
            return num2 * num1;
        } else if ("/".equals(oper)) {
            return num2 / num1;
        } else {
            return 0;
        }
    }
}
